﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace Jacaranda.Model
{
    class Mapper
    {
        public static List<Entity> RelationToEntity(DataTable table, Type type)
        {
            List<Entity> entities = new List<Entity>();

            for (int i = 0; i <= table.Rows.Count - 1; i++)
            {
                entities.Add(Activator.CreateInstance(type) as Entity);
            }


            FieldMetadata[] fields = Metadata.Type(type).Fields;

            foreach (DataColumn column in table.Columns)
            {
                FieldMetadata field = fields.FirstOrDefault(i => i.FieldName == column.ColumnName);
                if (field != null)
                {
                    for (int i = 0; i <= table.Rows.Count - 1; i++)
                    {
                        object cellValue = table.Rows[i][column];
                        field.SetValue(entities[i], DBNull.Value.Equals(cellValue) ? null : cellValue);
                    }
                }
            }

            foreach (Entity entity in entities)
            {
                entity.AfterLoad();
            }

            return entities;
        }

        public static void EntityToRelation(DataTable table, List<Entity> entities, Type type)
        {
            FieldMetadata[] fields = Metadata.Type(type).Fields;

            foreach (DataColumn column in table.Columns)
            {
                FieldMetadata field = fields.FirstOrDefault(i => i.FieldName == column.ColumnName);
                if (field != null)
                {
                    for (int i = 0; i <= entities.Count - 1; i++)
                    {
                        object fieldValue = field.GetValue(entities[i]);
                        table.Rows[i][column] = (fieldValue == null) ? DBNull.Value : fieldValue;
                    }
                }
            }
        }

        public static void SingleEntityToRelation(DataRow row, Entity entity)
        {
            FieldMetadata[] fields = Metadata.Type(entity.GetType()).Fields;

            foreach (DataColumn column in row.Table.Columns)
            {
                FieldMetadata field = fields.FirstOrDefault(i => i.FieldName == column.ColumnName);
                if (field != null)
                {
                    object fieldValue = field.GetValue(entity);
                    row[column] = (fieldValue == null) ? DBNull.Value : fieldValue;
                }
            }
        }
    }
}
